<?php

namespace Home\Controller;

class BuyerorderController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
//        $this->_user_id = 3;
//        $this->_user_name = session('visitor.user_name');

        $this->_order_mod = M('order');
        $this->_order_goods_mod = M('order_goods');
        $this->_member_mod = M('member');
        
    }

    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=get_list 获取当前用户的订单
     * 
     * @apiName 获取当前用户的购物车列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取当前用户的购物车列表
     * 
     * @apiParam {String} status 订单状态
     * 
     * @apiSuccess {String} order_id 订单ID
     * @apiSuccess {String} order_sn 订单编号
     * @apiSuccess {String} type 订单类型
     * @apiSuccess {String} seller_id 卖家ID
     * @apiSuccess {String} seller_name 卖家名称
     * @apiSuccess {String} buyer_id 买家ID
     * @apiSuccess {String} buyer_name 买家名称
     * @apiSuccess {String} status 订单状态
     * @apiSuccess {String} add_time 下单时间
     * @apiSuccess {String} payment_id 支付方式ID
     * @apiSuccess {String} payment_name 支付方式名称
     * @apiSuccess {String} pay_time 支付时间
     * @apiSuccess {String} invoice_no 发货物流号
     * @apiSuccess {String} auto_finished_time 自动收货时间
     * @apiSuccess {String} goods_amount 商品价格 
     * @apiSuccess {String} discount 减免价格
     * @apiSuccess {String} order_amount 订单价格
     * @apiSuccess {String} pd_amount 使用预付款金额
     * @apiSuccess {String} anonymous 产品数量
     * @apiSuccess {String} total_quantity 商品总数量
     * 
     * @apiSuccess {String} order_status.evaluate_status 是否评价(1.已评价2.未评价)
     * @apiSuccess {String} order_status.delay_status 是否显示延迟收货按钮
     * @apiSuccess {String} order_status.pay_status 是否显示支付按钮
     * @apiSuccess {String} order_status.confirm_status 是否显示确认按钮
     * @apiSuccess {String} order_status.cancel_status 是否显示取消按钮
     * 
     * @apiSuccess {String} order_goods.goods_id 产品ID
     * @apiSuccess {String} order_goods.goods_name 产品名称
     * @apiSuccess {String} order_goods.spec_id 规格ID
     * @apiSuccess {String} order_goods.specification 规格名称
     * @apiSuccess {String} order_goods.price 价格
     * @apiSuccess {String} order_goods.goods_old_price 产品原价
     * @apiSuccess {String} order_goods.quantity 产品数量
     * @apiSuccess {String} order_goods.goods_image 产品图片
     * @apiSuccess {String} order_goods.goods_type 产品类型
     * @apiSuccess {String} order_goods.refund_status 退款状态
     * @apiSuccess {String} order_goods.refund_id 退款ID
     * 
     */
    function get_list() {
        //统计页面-订单列表
        set_day_statistics_redis('view_order_list');
        $map['buyer_id'] = $this->_user_id;
        $status = I('request.status', '');
        if($status){
            $map['status'] = $status;
        }

        $order_list = $this->_order_mod
                ->field('order_sn,store_name,order_id,order_sn,type,seller_id,seller_id,seller_name,buyer_id,buyer_name,status,o.add_time,payment_id,payment_name,pay_time,invoice_no,express_company,finished_time,auto_finished_time,goods_amount,discount,order_amount,pd_amount,anonymous,evaluation_status')
                ->alias('o')
                ->where($map)
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'store s ON s.store_id = o.seller_id')
                ->order('o.add_time desc')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        $refund_mod = M('refund');
        if ($order_list) {
            //商品总量
            $total_quantity = 0;
            foreach ($order_list as $key => $order) {
//    ORDER_CANCELED = 0,//已取消
//    ORDER_SUBMITTED = 10,//已提交
//    ORDER_PENDING = 11,//待付款
//    ORDER_ACCEPTED = 20,//待发货
//    ORDER_SHIPPED = 30,//已发货
//    ORDER_FINISHED = 40,//已完成
//    ORDER_REFUND = 50//已退款
                if($order['status'] == 0){
                    $order_list[$key]['state_text'] = '已取消';
                }else if($order['status'] == 10){
                    $order_list[$key]['state_text'] = '已提交';
                }else if($order['status'] == 11){
                    $order_list[$key]['state_text'] = '待付款';
                }else if($order['status'] == 20){
                    $order_list[$key]['state_text'] = '待发货';
                }else if($order['status'] == 30){
                    $order_list[$key]['state_text'] = '已发货';
                }else if($order['status'] == 40){
                    $order_list[$key]['state_text'] = '已完成';
                }else if($order['status'] == 50){
                    $order_list[$key]['state_text'] = '已退款';
                }
                $order_goods = $this->_order_goods_mod
                        ->field('order_id,goods_id,goods_name,spec_id,specification,goods_old_price,price,price_total,quantity,goods_image,goods_type')
                        ->where('order_id=' . $order['order_id'])
                        ->select();
                foreach ($order_goods as $key2 => $goods) {
                    /* 是否申请过退款 */
                    $refund = $refund_mod->field('status,order_id')->where('order_id=' . $goods['order_id'] . ' and goods_id=' . $goods['goods_id'] . ' and spec_id=' . $goods['spec_id'])->find();
                    if ($refund) {
                        $order_goods[$key2]['refund_status'] = $refund['status'];
                        $order_goods[$key2]['refund_id'] = $refund['refund_id'];
                    }
                    $total_quantity += $goods['quantity'];
                }
                $order_list[$key]['total_quantity'] = $total_quantity;
                $order_list[$key]['order_goods'] = $order_goods;


                //设置列表状态
                if ($order['evaluation_status'] == 1) {
                    $order_list[$key]['button']['evaluate_status'] = 1; //1已评价
                } elseif ($order['evaluation_status'] == 0 && $order['status'] == ORDER_FINISHED && $goods['refund_status'] != 'SUCCESS' && $goods['refund_status'] != 'CLOSED') {
                    $order_list[$key]['button']['evaluate_status'] = 2; //2需评价
                } else {
                    $order_list[$key]['button']['evaluate_status'] = NULL;
                }

                //是否显示延迟收货按钮
                if ($order['status'] == ORDER_SHIPPED && $order['payment_code'] != 'cod' && $order['payment_code'] != 'bank' && $order['payment_code'] != 'post') {
                    $order_list[$key]['button']['delay_status'] = 1; //是否显示延迟收货
                } else {
                    $order_list[$key]['button']['delay_status'] = NULL;
                }
                //是否显示支付按钮
                if ($order['status'] == ORDER_PENDING) {
                    $order_list[$key]['button']['pay_status'] = 1;
                } else {
                    $order_list[$key]['button']['pay_status'] = NULL;
                }
                //是否显示确认收货
                if ($order['status'] == ORDER_SHIPPED) {
                    $order_list[$key]['button']['confirm_status'] = 1;
                } else {
                    $order_list[$key]['button']['confirm_status'] = NULL;
                }
                //是否显示取消订单
                if ($order['status'] == ORDER_PENDING || $order['status'] == ORDER_SUBMITTED) {
                    $order_list[$key]['button']['cancel_status'] = 1;
                } else {
                    $order_list[$key]['button']['cancel_status'] = NULL;
                }

            }
        }
        
        render('10000', '', array('order_list' => $order_list,));
    }
    
    
    
    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=status_list 获取当前状态列表
     * 
     * @apiName 获取当前状态列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取当前状态列表
     * 
     */
    function status_list(){
        
        $status_list = $this->_get_status_list();
        $result = array(); 
        foreach ($status_list as $key => $status) {
            $result[] = array(
                'key' => $key,
                'value' => $status,
            );
        }
        render('10000', '',array('status_list'=>  $result));
    }
    
    function _get_status_list()
    {
        return array(
            //10
            ORDER_SUBMITTED => '货到付款',
            //11
            ORDER_PENDING=>'待付款',
            //20
            ORDER_ACCEPTED=>'待发货',
            //30
            ORDER_SHIPPED=>'已发货',
            //40
            ORDER_FINISHED=>'已完成',
            //0
            ORDER_CANCELED=>'已取消',
            '50'=>'已退款',
//            ORDER_FINISHED=>'已退款',
        );
    }
    function _get_customs_list()
    {
        return array(

            0 => '未拆单',

            40 => '已拆单',

            50 => '支付报关中',

            61 => '支付报关成功',

            62 => '支付报关失败',

            63 => '身份校验失败',

            70 => '海关报关中',

            81 => '海关报关成功',

            82 => '海关报关失败',

            90 => '物流下单成功',

            91 => '物流收单成功',

            92 => '物流收货成功',

            93 => '物流下单失败',

            94 => '物流已接受信息',

            95 => '退运',

            96 => '清关放行',
        );
    }
     

    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=view 获取当前用户的订单详情
     * 
     * @apiName 获取当前用户的订单详情
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取当前用户的订单详情
     * 
     * @apiParam {String} order_id 订单ID
     * 
     * @apiSuccess {String} order_info.order_id 订单ID
     * @apiSuccess {String} order_info.order_sn 订单编号
     * @apiSuccess {String} order_info.type 订单类型
     * @apiSuccess {String} order_info.seller_id 卖家ID
     * @apiSuccess {String} order_info.seller_name 卖家名称
     * @apiSuccess {String} order_info.buyer_id 买家ID
     * @apiSuccess {String} order_info.buyer_name 买家名称
     * @apiSuccess {String} order_info.status 订单状态
     * @apiSuccess {String} order_info.add_time 下单时间
     * @apiSuccess {String} order_info.payment_id 支付方式ID
     * @apiSuccess {String} order_info.payment_name 支付方式名称
     * @apiSuccess {String} order_info.pay_time 支付时间
     * @apiSuccess {String} order_info.invoice_no 发货物流号
     * @apiSuccess {String} order_info.auto_finished_time 自动收货时间
     * @apiSuccess {String} order_info.goods_amount 商品价格 
     * @apiSuccess {String} order_info.discount 减免价格
     * @apiSuccess {String} order_info.order_amount 订单价格
     * @apiSuccess {String} order_info.pd_amount 使用预付款金额
     * @apiSuccess {String} order_info.anonymous 产品数量
     * 
     * @apiSuccess {String} order_detail.goods_list.goods_id 产品ID
     * @apiSuccess {String} order_detail.goods_list.goods_name 产品名称
     * @apiSuccess {String} order_detail.goods_list.spec_id 规格ID
     * @apiSuccess {String} order_detail.goods_list.specification 规格名称
     * @apiSuccess {String} order_detail.goods_list.price 价格
     * @apiSuccess {String} order_detail.goods_list.goods_old_price 产品原价
     * @apiSuccess {String} order_detail.goods_list.quantity 产品数量
     * @apiSuccess {String} order_detail.goods_list.goods_image 产品图片
     * @apiSuccess {String} order_detail.goods_list.goods_type 产品类型
     * @apiSuccess {String} order_detail.goods_list.refund_status 退款状态
     * @apiSuccess {String} order_detail.goods_list.refund_id 退款ID
     * 
     * @apiSuccess {String} order_detail.order_extm.order_id 订单ID
     * @apiSuccess {String} order_detail.order_extm.consignee 收件人
     * @apiSuccess {String} order_detail.order_extm.region_id 地区ID
     * @apiSuccess {String} order_detail.order_extm.region_name 地区名称
     * @apiSuccess {String} order_detail.order_extm.address 地址
     * @apiSuccess {String} order_detail.order_extm.zipcode 邮政编码
     * @apiSuccess {String} order_detail.order_extm.phone_mob 手机
     * @apiSuccess {String} order_detail.order_extm.shipping_id 物流ID
     * @apiSuccess {String} order_detail.order_extm.shipping_name 物流名称
     * @apiSuccess {String} order_detail.order_extm.shipping_fee 运费
     * 
     * @apiSuccess {String} order_detail.order_logs.log_id 订单日志ID
     * @apiSuccess {String} order_detail.order_logs.order_id 订单ID
     * @apiSuccess {String} order_detail.order_logs.operator 操作者
     * @apiSuccess {String} order_detail.order_logs.order_status 原订单状态
     * @apiSuccess {String} order_detail.order_logs.changed_status 改变订单状态
     * @apiSuccess {String} order_detail.order_logs.remark 备注
     * @apiSuccess {String} order_detail.order_logs.log_time 日志事件
     * @apiSuccess {String} order_detail.order_logs.order_log_status 日志状态
     * @apiSuccess {String} order_detail.order_logs.operator_type 操作类型
     * 
     */
    function view() {
        $order_id = I('request.order_id', 0, 'intval');
        if (empty($order_id)) {
            render('10500', '此订单不存在');
        }
        $map['buyer_id'] = $this->_user_id;
        $map['order_id'] = $order_id;

        $order_info = $this->_order_mod
                ->field('order_id,order_sn,type,seller_id,seller_id,seller_name,buyer_id,buyer_name,status,add_time,payment_id,payment_name,payment_code,ship_time,pay_time,invoice_no,express_company,finished_time,auto_finished_time,goods_amount,discount,order_amount,pd_amount,anonymous,evaluation_status')
                ->where($map)
                ->find();
        if (!$order_info) {
            render('10500', '此订单不存在');
        }
        //获取订单状态中文名称
        $status_list = $this->_get_status_list();
        $order_info['status_name'] = $status_list[$order_info['status']];
        //获取海关状态中文名称
        $status_list = $this->_get_customs_list();
        $order_info['customs_status_name'] = $status_list[$order_info['customs_status']];
        //格式化时间
        $order_info['add_time']=date('Y-m-d H:i:s',$order_info['add_time']);
        $order_info['pay_time']=date('Y-m-d H:i:s',$order_info['pay_time']);
        $order_info['finished_time']=date('Y-m-d H:i:s',$order_info['finished_time']);
        $order_info['auto_finished_time']=date('Y-m-d H:i:s',$order_info['auto_finished_time']);
        $order_info['ship_time']=date('Y-m-d H:i:s',$order_info['ship_time']);
        //链接
        $order_info['customer_url'] = C('SITE_URL').'/index.php?app=seller_order&act=view&order_id='.$order_id;

        $order_detail = $this->get_order_detail($order_id, $order_info);
        foreach ($order_detail['goods_list'] as $k => $v){
//            $order_info['price_amount'] = (string)round($order_info['price_amount'] +$v['price_amount'],2);
            $order_info['price_amount'] = (string)round($order_info['goods_amount'] - $v['tax_price_amount'],2);
            $order_info['coupon_price'] = (string)round($order_info['goods_amount'] - $v['price_total'],2);
            $order_info['tax_price_amount'] = (string)round($order_info['tax_price_amount'] +$v['tax_price_amount'],2);
            $order_info['price_total'] = (string)round($order_info['price_total'] +$v['price_total'],2);
        }
        $data = array(
            'order_info' => $order_info,
            'order_detail' => $order_detail,
        );
        render('10000', '', $data);
    }

    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=cancel_order 取消订单
     * 
     * @apiName 取消订单
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 取消订单
     * 
     * @apiParam {String} order_id 订单ID
     */
    function cancel_order() {
        $order_id = I('request.order_id', 0, 'intval');
        if (empty($order_id)) {
            render('19999', '此订单不存在');
        }
        $map['buyer_id'] = $this->_user_id;
        $map['order_id'] = $order_id;
        /* 只有待付款的订单可以取消 */
        $map['status'] = array('in', array(ORDER_PENDING, ORDER_SUBMITTED));
        $order_info = $this->_order_mod->where($map)->find();
        if (empty($order_info)) {
            render('19999', '此订单不存在');
        }
//        $url = ERP_URL.':443/API/Order/UpdateOrderStatus';
        $url = C('ERP_URL').'/api/order/UpdateOrderStatus';
        $data = array(
            'OrderStatusId'=>20,
            'OrderNo'=>$order_info['order_sn']
        );
        $rs = _curl_to_oms($url,$data);
        $res = M('order')
            ->join('ecm_order_goods on ecm_order.order_id = ecm_order_goods.order_id')
//            ->join('ecm_goods_spec on ecm_order_goods.spec_id = ecm_goods_spec.spec_id')
            ->where(array('ecm_order.order_id'=>$map['order_id']))
            ->find();
        $data_order['status'] = ORDER_CANCELED;
        $this->_order_mod->where($map)->save($data_order);
        if($order_info['coupon_id']){
            $coupon_id = $order_info['coupon_id'];
            $data_coupon['is_used'] = 0;
            $data_coupon['use_time'] = 0;
            $res_coupon_save = M('member_coupon')->where(array('coupon_id'=>$coupon_id))->save($data_coupon);
        }
        $res_save = M('goods_spec')->where(array('spec_id'=>$res['spec_id']))->setInc('stock');
        render('10000', '取消订单成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=confirm_order 确认订单
     * 
     * @apiName 确认订单
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 确认订单
     * 
     * @apiParam {String} order_id 确认订单
     * 
     */
    function confirm_order() {
        $order_id = I('request.order_id', 0, 'intval');
        if (!$order_id) {
            render('19999', '此订单不存在');
        }
        /* 只有已发货的订单可以确认 */
        $order_info = $this->_order_mod->where("order_id={$order_id} AND buyer_id=" . $this->_user_id . " AND status=" . ORDER_SHIPPED)->find();
        if (empty($order_info)) {
            render('19998', '此订单不存在');
        }
        $this->_order_mod->where('order_id=' . $order_id)->save(array('status' => ORDER_FINISHED, 'finished_time' => time()));


        /* 记录订单操作日志 */
        $order_log = M('order_log');
        $order_log->add(array(
            'order_id' => $order_id,
            'operator' => $this->_user_name,
            'order_status' => order_status($order_info['status']),
            'changed_status' => order_status(ORDER_FINISHED),
            'remark' => '买家确认订单',
            'log_time' => time(),
            'operator_type' => 'buyer',
        ));

        /* 更新定单状态 开始***************************************************** */
        $this->_account_log_mod = M('account_log');
        $account_log = $this->_account_log_mod->where("order_id='$order_id' and type=" . ACCOUNT_TYPE_BUY)->find();
        $sell_user_id = $order_info['seller_id']; //卖家ID
        $buyer_user_id = $account_log['user_id']; //买家ID
        if (empty($buyer_user_id) || empty($sell_user_id)) {
            //此处表示是卖家确实收到货款，金额没有通过预付款去支付
            render('10000', '确认收货成功');
        }

        if ($account_log['order_id'] == $order_id) {

            $temp_order = $this->_order_mod->where('order_id=' . $order_id)->find();
            $money = $temp_order['order_amount']; //定单价格

            $sell_money_row = $this->_member_mod->where('user_id=' . $sell_user_id)->find();
            $sell_money = $sell_money_row['money']; //卖家的资金
            $sell_money_dj = $sell_money_row['money_dj']; //卖家的冻结资金
            $new_money = $sell_money + $money;
            $new_money_dj = $sell_money_dj - $money;
            //更新数据
            $new_money_array = array(
                'money' => $new_money,
                'money_dj' => $new_money_dj,
            );
            $new_buyer_account_log = array(
                'money' => $money,
                'complete' => 1,
                'states' => 40,
            );
            $new_seller_account_log = array(
                'money' => $money,
                'complete' => 1,
                'states' => 40,
            );
            $this->_member_mod->where('user_id=' . $sell_user_id)->save($new_money_array);
            $this->_account_log_mod->where("order_id={$order_id} AND user_id={$sell_user_id}")->save($new_seller_account_log);
            $this->_account_log_mod->where("order_id={$order_id} AND user_id={$buyer_user_id}")->save($new_buyer_account_log);
        }

        /* 更新定单状态 结束***************************************************** */
        
        //为资金管理才可以扣除金额
        if ($order_info['payment_code'] != 'cod' && $order_info['payment_code'] != 'bank' && $order_info['payment_code'] != 'post') {
            /* 交易成功后,推荐者可以获得佣金  BEGIN */
            /*
             * 先忽略
             */
            /* 交易成功后,推荐者可以获得佣金  END */

            /* 用户确认收货后 扣除商城佣金 */
            D('Accountlog')->trade_charges($order_info);
        }
        
        /* 更新累计销售件数 */
        $goods_statistics_mod = M('goods_statistics');
        $order_goods = $this->_order_goods_mod->where('order_id=' . $order_id)->select();
        foreach ($order_goods as $goods) {
            $goods_statistics_mod->where('goods_id=' . $goods['goods_id'])->setInc('sales', $goods['quantity']);
        }
        
        /* 用户确认收货后 获得积分 */
        D('Integrallog')->change_integral_buy($order_info['buyer_id'], $order_info['goods_amount']);
        $res_member = M('member')->where(array('user_id'=>$order_info['buyer_id']))->find();
        if($res_member['referid']){
            //推荐人
            $res_refer = M('member')->where(array('user_id'=>$res_member['referid']))->find();
            if (!$res_refer){
                M('order')->rollback();
                return false;
            }
            if($res_refer['is_promoters'] == 1){
                //佣金
//                $res_config = M('mall_config')->where(array('code'=>'promotion_proportion'))->find();
//                if (!$res_config){
//                    render('10004', '网络错误');
//                }
//                $res_member_save = M('member')->where(array('user_id'=>$res_refer['user_id']))->save(array('commission'=>(float)$res_refer['commission']+(float)($res_config['value']*$order_info['order_amount'])));
//                if (!$res_member_save){
//                    render('10004', '网络错误');
//                }
                $res_detail_save = M('commission_detail')->where(array('order_id'=>$order_id,'sign'=>'+'))->save(array('order_finish_time'=>time()));
                if ($res_detail_save === false){
                    M('order')->rollback();
                    return false;
                }
//                $data_commission = array(
//                    'user_id' => $res_refer['user_id'],
//                    'sign' => '+',
//                    'commission_money' => $res_config['value']*$order_info['order_amount'],
//                    'finish_time' => time(),
//                    'remark' => '佣金结算'
//                );
//                $res_commission = M('commission')->add($data_commission);
//                if (!$res_commission){
//                    render('10004', '网络错误');
//                }
//                $data_commission_log = array(
//                    'user_id' => $res_refer['user_id'],
//                    'fans_id' => $res_member['user_id'],
//                    'sign' => '+',
//                    'order_id' => $order_info['order_id'],
//                    'order_money' => $order_info['order_amount'],
//                    'commission_money' => $res_config['value']*$order_info['order_amount'],
//                    'finish_time' => time()
//                );
//                $res_commission_log = M('commission_log')->add($data_commission_log);
//                if (!$res_commission_log){
//                    render('10004', '网络错误');
//                }
            }
        }
        $data_oms = array(
            'OrderNo' => $order_info['order_sn'],
            'OrderStatusId' => 1000
        );
        $url = C('FINISH_ORDER');
        _curl_to_oms($url,$data_oms);
        render('10000', '确认收货成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=evaluate 评价订单
     * 
     * @apiName 评价订单
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 评价订单
     * 
     * @apiParam {String} order_id 订单ID
     * 
     */
    function evaluate() {
        $order_id = I('request.order_id', 0, 'intval');
        if (!$order_id) {
            render('19999', '此订单不存在');
        }
        /* 验证订单有效性 */
        $order_info = $this->_order_mod->where("order_id={$order_id} AND buyer_id=" . $this->_user_id)->find();

        if (empty($order_info)) {
            render('19999', '此订单不存在');
        }
        if ($order_info['status'] != ORDER_FINISHED) {
            /* 不是已完成的订单，无法评价 */
            render('19999', '订单未完成不能评价');
        }
        if ($order_info['evaluation_status'] != 0) {
            render('19999', '订单已评价');
        }
        /*
        foreach ($_POST['evaluations'] as $rec_id => $evaluation) {
            if ($evaluation['evaluation'] <= 0 || $evaluation['evaluation'] > 3) {
                render('19999', '评分错误');
            }
            switch ($evaluation['evaluation']) {
                case 3:
                    $credit_value = 1;
                    break;
                case 1:
                    $credit_value = -1;
                    break;
                default:
                    $credit_value = 0;
                    break;
            }
            $evaluations[intval($rec_id)] = array(
                'evaluation' => $evaluation['evaluation'],
                'evaluation_desc' => in_array($evaluation['evaluation_desc'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_desc'] : 5, #描述相符评分
                'evaluation_service' => in_array($evaluation['evaluation_service'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_service'] : 5, #服务动态评分
                'evaluation_speed' => in_array($evaluation['evaluation_speed'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_speed'] : 5, #发货速度评分
                'comment' => $evaluation['comment'],
                'credit_value' => $credit_value
            );
        }
         * 
         */
        
        $goods_list = $this->_order_goods_mod->where('order_id=' . $order_id)->select();
        $goods_statistics_mod = M('goods_statistics');
        foreach ($goods_list as  $goods) {
            $evaluation = $_POST['evaluations'][$goods['rec_id']];
            if ($evaluation['evaluation'] <= 0 || $evaluation['evaluation'] > 5) {
                render('19999', '未选择评分');
            }
            switch ($evaluation['evaluation']) {
                case 3:
                    $credit_value = 1;
                    break;
                case 1:
                    $credit_value = -1;
                    break;
                default:
                    $credit_value = 0;
                    break;
            }
            $data = array(
                'evaluation' => $evaluation['evaluation'],
                /* 新增 店铺动态评分 begin */
                'evaluation_desc' => in_array($evaluation['evaluation_desc'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_desc'] : 5, #描述相符评分
                'evaluation_service' => in_array($evaluation['evaluation_service'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_service'] : 5, #服务动态评分
                'evaluation_speed' => in_array($evaluation['evaluation_speed'], array("1", "2", "3", "4", "5",)) ? $evaluation['evaluation_speed'] : 5, #发货速度评分
                /* 新增 店铺动态评分 end */
                'comment' => $evaluation['comment'],
                'credit_value' => $credit_value
            );
            //更新得分
            $this->_order_goods_mod->where("rec_id=".$goods['rec_id']." AND order_id=".$order_id)->save($data);
            //更新统计
            $goods_statistics_mod->where('goods_id='.$goods['goods_id'])->setInc('comments');
        }

        /* 更新订单评价状态 */
        $this->_order_mod->where('order_id=' . $order_id)->save(array(
            'evaluation_status' => 1,
            'evaluation_time' => time()
        ));
        //更新店铺统计得分
        D('store')->update_recount($order_info['seller_id']);
        render('10000', '评价成功');
    }

    function test()
    {
        $_POST['evaluations'][2]['evaluation'] = 3;
        $_POST['evaluations'][2]['comment'] = '商品2的内容';
        $_POST['evaluations'][2]['evaluation_desc'] = '5';
        $_POST['evaluations'][2]['evaluation_service'] = '5';
        $_POST['evaluations'][2]['evaluation_speed'] = '5';
        $_POST['evaluations'][3]['evaluation'] = 3;
        $_POST['evaluations'][3]['comment'] = '商品2的内容';
        $_POST['evaluations'][3]['evaluation_desc'] = '5';
        $_POST['evaluations'][3]['evaluation_service'] = '5';
        $_POST['evaluations'][3]['evaluation_speed'] = '5';
        $_POST['evaluations'][4]['evaluation'] = 3;
        $_POST['evaluations'][4]['comment'] = '商品2的内容';
        $_POST['evaluations'][4]['evaluation_desc'] = '5';
        $_POST['evaluations'][4]['evaluation_service'] = '5';
        $_POST['evaluations'][4]['evaluation_speed'] = '5';
    }
    
    /**
     * @api {get} /index.php?m=Home&c=Buyerorder&a=delay 延长收货
     * 
     * @apiName 延长收货
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 延长收货
     * 
     * @apiParam {String} order_id 订单ID
     * 
     */
    function delay() {
        $order_id = I('request.order_id', 0, 'intval');
        if (!$order_id) {
            render('19999', '此订单不存在');
        }
        /* 验证订单有效性 */
        $order_info = $this->_order_mod->where("order_id={$order_id} AND buyer_id=" . $this->_user_id)->find();
        if (empty($order_info)) {
            render('19999', '此订单不存在');
        }

        if ($order_info['status'] != ORDER_SHIPPED) {
            render('19999', '此订单状态错误');
        }
        if ($order_info['auto_finished_time'] - time() > 3 * 3600 * 24) {
            render('19999', '自动收货日期前三天才可延长收货时间');
        }

        //自动延长3天
        $data = array(
            'auto_finished_time' => $order_info['auto_finished_time'] + 3 * 3600 * 24,
        );
        $this->_order_mod->where('order_id=' . $order_id)->save($order_id, $data);
        render('19999', '已延长收货3天');
    }

    private function get_order_detail($order_id, $order_info) {
        //获取商品列表
        $goods_list = $this->_order_goods_mod
                ->field('rec_id,order_id,goods_id,goods_name,spec_id,specification,goods_old_price,price,quantity,goods_image,goods_type,price_amount,tax_price_amount,price_total')
                ->where('order_id=' . $order_id)
                ->select();
        if ($goods_list) {
            foreach ($goods_list as $key => $goods) {
                $refund = M('refund')->where('order_id=' . $goods['order_id'] . ' and goods_id=' . $goods['goods_id'] . ' and spec_id=' . $goods['spec_id'])->find();
                if ($refund) {
                    $goods_list[$key]['refund_status'] = $refund['status'];
                    $goods_list[$key]['refund_id'] = $refund['refund_id'];

                    switch ($refund['status']) {
                        case 'SUCCESS':
                            $goods_list[$key]['refund_name'] = '退款成功';
                            break;
                        case 'CLOSED':
                            $goods_list[$key]['refund_name'] = '退款关闭';
                            break;
                        case 'FAILED':
                            $goods_list[$key]['refund_name'] = '退款失败';
                            break;
                        default:
                            $goods_list[$key]['refund_name'] = '退款中';
                            break;
                    }
                } else {
                    //如果不是国内货物不给退
                    $res = M('goods_spec')->join('left join ecm_storestock on ecm_goods_spec.spec_3value = ecm_storestock.storestock_id')->where(array('ecm_goods_spec.spec_id'=>$goods['spec_id']))->find();
                    if ($res['stock_style'] == 3 && ($order_info['status'] == ORDER_ACCEPTED || $order_info['status'] == ORDER_SHIPPED || ($order_info['status'] == ORDER_FINISHED && $order_info['finished_time'] >= time() - 86400*7))) {
                        $goods_list[$key]['refund_status'] = 'ADD';
                        $goods_list[$key]['refund_id'] = 0;
                        $goods_list[$key]['refund_name'] = '申请退款';
                    }
                }
                //WAIT_SELLER_AGREE 等待卖家同意  WAIT_ADMIN_AGREE 等待管理员同意  SUCCESS 退款成功  CLOSED 退款关闭  FAILED 退款失败 ADD新增退款
            }
        }
        $data['goods_list'] = $goods_list;

        /* 配关信息 */
        $order_extm_mod = M('order_extm');
        $data['order_extm'] = $order_extm_mod->where('order_id=' . $order_id)->find();
        /* 支付方式信息 */
        if ($order_info['payment_id']) {
            $payment_mod = M('payment');
            $payment_info = $payment_mod->where("payment_id={$order_info['payment_id']}")->find;
            $data['payment_info'] = $payment_info;
        }
        /* 订单操作日志 */
        $order_log_mod = M('order_log');
        $data['order_logs'] = $order_log_mod->where("order_id = {$order_id}")->select();
        return $data;
    }

}
